package utils;

import java.io.File;
import java.lang.reflect.Method;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

import demo.WeatherForecastService;

public class AddressUtils {
	public static String getCityInfo(String ip) {

		// db
		String dbPath = AddressUtils.class.getResource("/ip2region.db").getPath();

		File file = new File(dbPath);
		if (file.exists() == false) {
			System.out.println("Error: Invalid ip2region.db file");
		}

		// 查询算法
		int algorithm = DbSearcher.BTREE_ALGORITHM; // B-tree
		// DbSearcher.BINARY_ALGORITHM //Binary
		// DbSearcher.MEMORY_ALGORITYM //Memory
		try {
			DbConfig config = new DbConfig();
			DbSearcher searcher = new DbSearcher(config, dbPath);

			// define the method
			Method method = null;
			switch (algorithm) {
			case DbSearcher.BTREE_ALGORITHM:
				method = searcher.getClass().getMethod("btreeSearch", String.class);
				break;
			case DbSearcher.BINARY_ALGORITHM:
				method = searcher.getClass().getMethod("binarySearch", String.class);
				break;
			case DbSearcher.MEMORY_ALGORITYM:
				method = searcher.getClass().getMethod("memorySearch", String.class);
				break;
			}

			DataBlock dataBlock = null;
			if (Util.isIpAddress(ip) == false) {
				System.out.println("Error: Invalid ip address");
			}

			dataBlock = (DataBlock) method.invoke(searcher, ip);
			return dataBlock.getRegion();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static void main(String[] args) throws Exception {
		//获取本机IP地址
		String localIP = IPUtils.getLocalIP();
		System.out.println(localIP);
		//String cityInfo = getCityInfo("218.88.232.0");
		//获取城市信息：中国|西南|四川省|遂宁市|电信
		String cityInfo = getCityInfo(localIP);
		System.out.println(cityInfo);
		if (cityInfo.contains("内网")) {
			//判断内网IP，不能查看天气信息
			System.out.println("当前为内网IP不能查看位置信息");
		} else {
			//外网信息
			String[] s = cityInfo.split("\\|");
			// 获取城市当前城市
			System.out.println(s[3]);
			String cityName = s[3].substring(0, s[3].length()-1);
			System.out.println("当前城市名称"+cityName);
			// 调用天气webService获取天气信息
			System.out.println("======程序启动======");
			String result[] = WeatherForecastService.QueryWeatherForecastInfo(cityName);
			for (String r : result)
				//打印天气信息
				System.out.println(r);
			System.out.println("======程序结束======");
		}
	}
}
